package com.mustafaiev.tair.cts.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

import com.mustafaiev.tair.constant.Attributes;

public class CostsTrackingSystemAuthenticationFilter extends
		AbstractAuthenticationProcessingFilter {

	@Override
	public void setSessionAuthenticationStrategy(
			final SessionAuthenticationStrategy sessionStrategy) {
		super.setSessionAuthenticationStrategy(sessionStrategy);
	}

	protected CostsTrackingSystemAuthenticationFilter() {
		super("/j_spring_security_check");
	}

	@Override
	public Authentication attemptAuthentication(
			final HttpServletRequest request, final HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		final UsernamePasswordAuthenticationToken authenticationToken = getAuthToken(request);

		return super.getAuthenticationManager().authenticate(
				authenticationToken);
	}

	private UsernamePasswordAuthenticationToken getAuthToken(
			final HttpServletRequest request) {
		final String password = request.getParameter(Attributes.J_PASSWORD);
		final String username = request.getParameter(Attributes.J_USERNAME);
		final UsernamePasswordAuthenticationToken authenticationToken = new CostsTrackingSystemAuthToken(
				username, password);
		return authenticationToken;
	}
}
